package com.niit.controller;

import com.niit.apis.*;
import com.niit.entity.*;
import com.niit.utils.Result;
import com.niit.utils.exception.UnauthorizedException;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping
public class PageController {
	/**
	 * 登录/注册页面
	 */
	@GetMapping("/")
	public String homepage(HttpSession session){
		if(session.getAttribute("account") instanceof Admin){
			return "redirect:/admin/index";
		}else if(session.getAttribute("account") instanceof User){
			return "redirect:/user/index";
		}
		return "redirect:/login";
	}
	@GetMapping("/index")
	public String index(){
		return "/index";
	}
	@GetMapping("/login")
	public String login(@RequestParam(required = false) String error, Model model){
		model.addAttribute("message", error);
		return "login";
	}

	/**
	 * 后台页面
	 */
	@Controller
	@RequestMapping("/admin")
	public static class AdminIndexPageController {
		@Autowired
		private UserFeignApi userFeignApi;
		@Autowired
		private NotificationFeignApi notificationFeignApi;
		//后台首页
		@GetMapping("/index")
		public String indexAdmin(Model model){
			List<Menu> menuList = userFeignApi.getAllMenus();
			model.addAttribute("menuList", menuList);
			return "admin/index";
		}
		//默认欢迎
		@GetMapping("/welcome")
		public String welcome(){
			return "admin/welcome-page";
		}
		//个人信息
		@GetMapping("/info")
		public String info(Model model, HttpSession session) {
			Object account = session.getAttribute("account");

			if (account instanceof Admin admin) {
				Info info = userFeignApi.getAdmin(admin.getId()).getInfo();
				model.addAttribute("info", info);
			}
			return "/admin/info";
		}
		@GetMapping("/info-manager")
		public String infoManager() {
			return "/admin/info-manager";
		}

		//公告
		@GetMapping("/notification")
		public String getNotificationList() {
			return "/admin/notification";
		}
		@GetMapping("/company")
		public String company() {
			return "/admin/company";
		}
		@GetMapping("/user")
		public String seeker() {
			return "/admin/user";
		}

		//职位管理
		@GetMapping("/job-management")
		public String jobManagement() {
			return "/admin/job-management";
		}

	}

	/**
	 * 前台页面
	 */
	@Controller
	@RequestMapping("/user")
	public static class UserIndexPageController {
		@Autowired
		private NotificationFeignApi notificationFeignApi;
		@Autowired
		private UserFeignApi userFeignApi;
		@Autowired
		private JobFeignApi jobFeignApi;
        @Autowired
        private ApplicationFeignApi applicationFeignApi;
		@Autowired
		private MessageFeignApi messageFeignApi;

		//首页
		@GetMapping("/index")
		public String indexUser() {
			return "/index";
		}
		//个人信息
		@GetMapping("/info")
		public String info(Model model, HttpSession session) {
			Object account = session.getAttribute("account");
			if (account instanceof User user) {
				User user1 = userFeignApi.getUser(user.getId());
				model.addAttribute("info", user1.getInfo());
				model.addAttribute("company", user1.getCompany());
			}
			return "/info";
		}
		//公告
		@GetMapping("/notification")
		public String getNotification(Model model, HttpSession session){
			Integer loginType = (Integer) session.getAttribute("loginType");
			Page<Notification> notificationPage = notificationFeignApi.findNotifications(null, null, null, 1, 10, loginType);
			model.addAttribute("notifications", notificationPage.getContent());
			return "/notification/notification-list";
		}

		@GetMapping("/notification/view/{id}")
		public String getNotificationView(@PathVariable Integer id, Model model, HttpSession session) {
			Object account = session.getAttribute("account");
			if (account instanceof User user) {
				notificationFeignApi.markAsRead(id, user.getId());
			}
			Notification notification = notificationFeignApi.getNotificationView(id);
			model.addAttribute("notification", notification);
			return "/notification/notification-view";
		}


		@GetMapping("apply-job")
		public String applyJob(Model model){
			//求职者申请职位
			model.addAttribute("applies",applicationFeignApi.getApplications());
			return "/apply/apply-job";
		}

		@GetMapping("job-application")
		public String jobApplication(Model model , HttpSession session){
			//验证招聘者身份
			User account = (User) session.getAttribute("account");
			if(account==null){
				throw new RuntimeException("请先登录");
			}else {
				//获取该用户收到的申请记录
				model.addAttribute("applies", applicationFeignApi.getCompanyApplications(account));
			}
			return "/apply/job-application";
		}

		@GetMapping("application-page")
		public String applicationPage(Model model, HttpSession session){
			//求职者查看自己的申请记录
			User account = (User) session.getAttribute("account");//登录的用户
			if(account==null){
					throw new RuntimeException("请先登录");
			}else{
				//获取该用户的申请记录
				model.addAttribute("applies", applicationFeignApi.getSeekerApplications(account));
			}

			return "/apply/application-page";
		}
		@GetMapping("application-detail/{id}")
		public String applicationDetail(@PathVariable int id, Model model){
			//公用申请详情页
			Application application = applicationFeignApi.getApplicationById(id);
			model.addAttribute("apply", application);
			return "/apply/application-detail";
		}


		@GetMapping("job-list")
		public String jobList(Model model, HttpSession session) {
			//根据登录用户获取该用户所发布的职位列表
			User account = (User) session.getAttribute("account");//登录的用户
			if (account == null) {
				throw new RuntimeException("请先登录");
			}else {
				//获取该用户发布的职位列表
				model.addAttribute("jobs", jobFeignApi.getMyJobs(account));
			}
			return "job/job-list";
		}
		@GetMapping("/job-edit/{id}")
		public String jobEdit(Model model, @PathVariable int id) {
			model.addAttribute("job", jobFeignApi.getJob(id));
			return "job/job-edit";
		}

		@GetMapping("/job-view/{id}")
		public String jobView(Model model, @PathVariable int id) {
			model.addAttribute("job", jobFeignApi.getJob(id));
			return "job/job-view";
		}

		@GetMapping("/jobs-page")
		public String jobsPage(
				@RequestParam(required = false) String location,
				@RequestParam(required = false) String salaryRange,
				@RequestParam(required = false) String keyword,
				@RequestParam(defaultValue = "1") int page,
				@RequestParam(defaultValue = "10") int size,
				Model model) {

			Page<Job> jobPage = jobFeignApi.searchJobByCondition(location, salaryRange, keyword, page, size);

			model.addAttribute("jobs", jobPage.getContent());
			model.addAttribute("totalItems", jobPage.getTotalElements());
			model.addAttribute("totalPages", jobPage.getTotalPages());
			model.addAttribute("currentPage", page);
			model.addAttribute("pageSize", size);

			// 回显查询条件
			model.addAttribute("location", location);
			model.addAttribute("salaryRange", salaryRange);
			model.addAttribute("keyword", keyword);

			return "job/jobs-page";
		}

		@GetMapping("new-job")
		public String newJob(){
			return "/job/new-job";
		}

		@GetMapping("/contacts")
		public String contacts(Model model, HttpSession session){
			Object account = session.getAttribute("account");
			if(account instanceof User user){
				List<Message> message = messageFeignApi.getContacts(user.getId());
				model.addAttribute("message", message);
				model.addAttribute("currentUserId", user.getId());
				return "message/contacts";
			}
			throw new UnauthorizedException("用户登录状态异常");
		}
		// 获取聊天页面
		@GetMapping("/chat")
		public String getChatPage(@RequestParam Integer senderId,
								  @RequestParam Integer receiverId,
								  Model model) {
			//根据发送者和接收者获取messageObjectID
			MessageObject messageObject = messageFeignApi.findOrCreateMessageObject(senderId, receiverId);
			// 获取聊天记录
			List<Message> messages = messageFeignApi.getChatMessages(senderId, receiverId);
			// 获取接收者名称
			String username = messageObject.getReceiver().getInfo().getUsername();
			String receiverName = username == null ? "未知用户" : username;
			model.addAttribute("senderId", senderId);
			model.addAttribute("receiverId", receiverId);
			model.addAttribute("receiverName", receiverName);
			model.addAttribute("messages", messages);
			//messageObjectID
			model.addAttribute("messageObjectID", messageObject.getId());
			return "message/chat";
		}
	}

}
